package com.team.dao.impl;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import com.team.dao.EquipmentStockDao;
import com.team.entity.Equipment;
import com.team.entity.EquipmentStock;

@Repository
public class EquipmentStockDaoImpl implements EquipmentStockDao{
	@Resource
	private SessionFactory sessionFactory;

	
	public EquipmentStock selectEquipmentStockByName(String name) {
		String hql="from EquipmentStock where name=?";
		try{
			Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, name);
			EquipmentStock equipmentStock =(EquipmentStock) query.uniqueResult();
			return equipmentStock;
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

	
	public void saveEquipmentStock(EquipmentStock equipmentStock) {
		try {
			this.sessionFactory.getCurrentSession().save(equipmentStock);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
	public void updateEquipmentaddStock(EquipmentStock equipmentStock) {
		String hql="update EquipmentStock set stock=stock+?,price=price+? where name=?";
		try{
			Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, equipmentStock.getStock());
			query.setParameter(1, equipmentStock.getPrice());
			query.setParameter(2, equipmentStock.getName());
			query.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

	
	public void updateAssetPrice(Integer price) {
		String hql="update Asset set price=price-? where id=1";
		try{
			Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, price);
			query.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
	}


	public Integer seleteAsset() {
		String hql ="select price from Asset where id=1";
		try {
			Integer price =(Integer) this.sessionFactory.getCurrentSession().createQuery(hql).uniqueResult();
			
			return price;
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public void updateEquipmentsubStock(Equipment equipment) {
		String hql="update EquipmentStock set price=price-?,stock=stock-1 where name=?";
		try{
			Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
			query.setParameter(0, equipment.getPrice());
			query.setParameter(1, equipment.getName());
			query.executeUpdate();
		}catch(Exception e){
			
		}
		
	}

}
